package com.example.daxiguaforharmony;

import com.example.daxiguaforharmony.manager.CrossDeviceManager;
import com.example.daxiguaforharmony.slice.*;
import com.example.daxiguaforharmony.utils.DbKvManager;
import com.example.daxiguaforharmony.utils.LogUtil;
import ohos.aafwk.ability.*;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import ohos.agp.components.ComponentProvider;
import ohos.app.Context;
import ohos.bundle.IBundleManager;
import com.example.daxiguaforharmony.widget.controller.FormController;
import com.example.daxiguaforharmony.widget.controller.FormControllerManager;
import ohos.data.orm.OrmPredicates;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONObject;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Full screen ability
 */
public class MainAbility extends Ability implements IAbilityContinuation{
    public static final int DEFAULT_DIMENSION_2X2 = 2;
    private static final int DEFAULT_DIMENSION_2X4 = 3;
    private static final String EMPTY_STRING = "";
    private static final int INVALID_FORM_ID = -1;
    private static final long SEND_PERIOD = 1000L;
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.DEBUG, 0x0, MainAbility.class.getName());
    private String topWidgetSlice;

    DbKvManager dbKvManager;
    private long formId;
    private ProviderFormInfo formInfo;

    //private static final String PERMISSION_DATASYNC = "ohos.permission.DISTRIBUTED_DATASYNC";
    //private static final int MY_PERMISSION_REQUEST_CODE = 1;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        // 开发者显示声明需要使用的权限
        requestPermissionsFromUser(new String[]{"ohos.permission.DISTRIBUTED_DATASYNC"}, 0);
        //super.setMainRoute(MainAbilitySlice.class.getName());
        //super.setMainRoute(GameAbilitySlice.class.getName());
        super.setMainRoute(LoadingAbilitySlice.class.getName());
        //super.setMainRoute(ResultsAbilitySlice.class.getName());
        //super.setMainRoute(TestAbilitySlice.class.getName());

        // set the action route
        addActionRoute("action.game", GameAbilitySlice.class.getName());
        addActionRoute("action.results", ResultsAbilitySlice.class.getName());
        addActionRoute("action.loading", LoadingAbilitySlice.class.getName());
        addActionRoute("action.privacy", PrivacyAbilitySlice.class.getName());
        addActionRoute("action.desc", InstructionAbilitySlice.class.getName());

//        if (verifySelfPermission(PERMISSION_DATASYNC) != IBundleManager.PERMISSION_GRANTED) {
//            if (canRequestPermission(PERMISSION_DATASYNC)) {
//                requestPermissionsFromUser(new String[] {PERMISSION_DATASYNC}, MY_PERMISSION_REQUEST_CODE);
//            }
//        }

        dbKvManager = new DbKvManager(this.getContext());

        if (intentFromWidget(intent)) {
            topWidgetSlice = getRoutePageSlice(intent);
            if (topWidgetSlice != null) {
                setMainRoute(topWidgetSlice);
            }
        }
        //startTimer();
        //stopAbility(intent);
    }
    @Override
    protected ProviderFormInfo onCreateForm(Intent intent) {
        HiLog.info(TAG, "onCreateForm===");
        if (intent == null) {
            return new ProviderFormInfo();
        }
        // 获取卡片id
        formId = INVALID_FORM_ID;
        if (intent.hasParameter(AbilitySlice.PARAM_FORM_IDENTITY_KEY)) {
            formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        } else {
            return new ProviderFormInfo();
        }
        // 获取卡片名称
        String formName = EMPTY_STRING;
        if (intent.hasParameter(AbilitySlice.PARAM_FORM_NAME_KEY)) {
            formName = intent.getStringParam(AbilitySlice.PARAM_FORM_NAME_KEY);
        }
        // 获取卡片规格
        int dimension = DEFAULT_DIMENSION_2X2;
        if (intent.hasParameter(AbilitySlice.PARAM_FORM_DIMENSION_KEY)) {
            dimension = intent.getIntParam(AbilitySlice.PARAM_FORM_DIMENSION_KEY, DEFAULT_DIMENSION_2X2);
        }
        int layoutId = ResourceTable.Layout_form_image_with_information_widget_2_2;
        if (dimension == DEFAULT_DIMENSION_2X4) {
            layoutId = ResourceTable.Layout_form_image_with_information_widget_2_2;
        }
        formInfo = new ProviderFormInfo(layoutId, this);
        // 存储卡片信息
        //Form form = new Form(formId, formName, dimension);
        //ComponentProvider componentProvider = ComponentProviderUtils.getComponentProvider(form, this);
        //formInfo.mergeActions(componentProvider);

        //long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        //String formName = intent.getStringParam(AbilitySlice.PARAM_FORM_NAME_KEY);
        //int dimension = intent.getIntParam(AbilitySlice.PARAM_FORM_DIMENSION_KEY, DEFAULT_DIMENSION_2X2);
        HiLog.info(TAG, "onCreateForm: formId===" + formId + ",formName=" + formName);
//        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
//        FormController formController = formControllerManager.getController(formId);
//        formController = (formController == null) ? formControllerManager.createFormController(formId,formName, dimension) : formController;

        // 1. 获取自定义数据
        //IntentParams intentParams = intent.getParam(AbilitySlice.PARAM_FORM_CUSTOMIZE_KEY);
        // 2. 从intentParams中获取是否支持背景模糊
        //boolean isSupport = (boolean) intentParams.getParam("fa_card_background_blur_support");

        int specificationId = intent.getIntParam(AbilitySlice.PARAM_FORM_DIMENSION_KEY, 0);
        HiLog.info(TAG, "onCreateForm===: " + formId + " " + formName + " " + specificationId);
        // 开发者需要根据卡片的名称以及外观规格获取对应的xml布局并构造卡片对象，此处ResourceTable.Layout_form_ability_layout_2_2仅为示例
        //ProviderFormInfo formInfo = new ProviderFormInfo(ResourceTable.Layout_form_image_with_information_widget_2_2, this);
        // 获取卡片信息
        //String formData = getInitFormData(formName, specificationId);
        dbKvManager = new DbKvManager(this.getContext());
        String score1 = dbKvManager.read("score");
        System.out.println("onCreateForm 得分2======="+score1);
        score1 = score1.equals(null) ?"0":score1;
        score1 = score1.equals("") ?"0":score1;
        System.out.println("onCreateForm 得分2======="+score1);
        String score_high = dbKvManager.read("score_high");
        score_high = score_high.equals("") || score_high.equals("0") ?score1:score_high;
        System.out.println("onCreateForm最高得分2======="+score_high);
        //String formData = "1289";
        ComponentProvider componentProvider = new ComponentProvider();
        componentProvider.setText(ResourceTable.Id_text_title, score_high);
        formInfo.mergeActions(componentProvider);
        //......
        System.out.println("--------创建卡片===启动ServiceAbility 并通过intent传入formId");

        //启动ServiceAbility 并通过intent传入formId
        Intent intent2 = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withBundleName(getBundleName())
                .withAbilityName(GameServiceAbility.class.getName())
                .build();
        intent2.setOperation(operation);
        intent2.setParam("formId",formId);
        startAbility(intent2);
        //-------

        HiLog.info(TAG, "onCreateForm finish===.......");

        return formInfo;
        //return formController.bindFormData();
    }

    @Override
    protected void onUpdateForm(long formId) {
        HiLog.info(TAG, "onUpdateForm 开始===");
        super.onUpdateForm(formId);
//        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
//        FormController formController = formControllerManager.getController(formId);
//        formController.updateFormData(formId);

        // 开发者需要根据卡片的名称以及外观规格获取对应的xml布局并构造卡片对象，此处ResourceTable.Layout_form_ability_layout_2_2仅为示例
        //ProviderFormInfo formInfo = new ProviderFormInfo(ResourceTable.Layout_form_image_with_information_widget_2_2, this);
        // 获取卡片信息
        //String formData = getInitFormData(formName, specificationId);
        dbKvManager = new DbKvManager(this.getContext());
        String score1 = dbKvManager.read("score");
        score1 = score1.equals(null) ?"0":score1;
        score1 = score1.equals("") ?"0":score1;
        System.out.println("onUpdateForm 得分2======="+score1);
        String score_high = dbKvManager.read("score_high");
        score_high = score_high.equals("") || score_high.equals("0") ?score1:score_high;
        System.out.println("onUpdateForm 最高得分2======="+score_high);
        //String formData = "1289";
        ComponentProvider componentProvider = new ComponentProvider(ResourceTable.Layout_form_image_with_information_widget_2_2, this);
        componentProvider.setText(ResourceTable.Id_text_title, score_high);
        //formInfo.mergeActions(componentProvider);

        try {
            //Long updateFormId = form.getFormId();
            updateForm(formId, componentProvider);
        } catch (FormException e) {
            // 删除不存在的卡片
            //DatabaseUtils.deleteFormData(formId, connect);
            LogUtil.error(MainAbility.class.getName(),"onUpdateForm updateForm error");
        }
        //......
        HiLog.info(TAG, "onUpdateForm finish===.......");
    }



    @Override
    protected void onDeleteForm(long formId) {
        HiLog.info(TAG, "onDeleteForm: formId===" + formId);
        super.onDeleteForm(formId);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        formControllerManager.deleteFormController(formId);
    }

    @Override
    protected void onTriggerFormEvent(long formId, String message) {
        HiLog.info(TAG, "onTriggerFormEvent: " + message);
        super.onTriggerFormEvent(formId, message);

        System.out.println("--------点击卡片===");
        System.out.println(message);

        //启动ServiceAbility 并通过intent传入formId
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withBundleName(getBundleName())
                .withAbilityName(GameServiceAbility.class.getName())
                .build();
        intent.setOperation(operation);
        intent.setParam("formId",formId);
        startAbility(intent);
        //-------

//        ZSONObject params = ZSONObject.stringToZSON(message);
//        String content = params.getString("itemContent");
//        System.out.println(content);
//        FormBindingData bindingData = new FormBindingData(params);
        dbKvManager = new DbKvManager(this.getContext());
        String score1 = dbKvManager.read("score");
        score1 = score1.equals(null) ?"0":score1;
        score1 = score1.equals("") ?"0":score1;
        System.out.println("onUpdateForm 得分2======="+score1);
        String score_high = dbKvManager.read("score_high");
        score_high = String.valueOf(score_high);
        score_high = score_high.equals(null) ?score1:score_high;
        score_high = score_high.isEmpty() ?score1:score_high;
        System.out.println("onUpdateForm 最高得分2======="+score_high);
        //String formData = "1289";
        int layoutId = ResourceTable.Layout_form_image_with_information_widget_2_2;

        ComponentProvider componentProvider = new ComponentProvider(layoutId, this.getContext());
        componentProvider.setText(ResourceTable.Id_text_title, score_high);

        try {
            //updateForm(formId,bindingData);
            updateForm(formId,componentProvider);
        } catch (FormException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onNewIntent(Intent intent) {
        if (intentFromWidget(intent)) { // Only response to it when starting from a service widget.
            String newWidgetSlice = getRoutePageSlice(intent);
            if (topWidgetSlice == null || !topWidgetSlice.equals(newWidgetSlice)) {
                topWidgetSlice = newWidgetSlice;
                restart();
            }
        }
    }

    @Override
    public void onBackground() {
        super.onBackground();
        HiLog.info(TAG, "MainAbility::onBackground");
    }

    @Override
    public void onStop() {
        super.onStop();
        HiLog.info(TAG, "MainAbility::onStop");
    }

    private boolean intentFromWidget(Intent intent) {
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        return formId != INVALID_FORM_ID;
    }

    private String getRoutePageSlice(Intent intent) {
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        if (formId == INVALID_FORM_ID) {
            return null;
        }
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        if (formController == null) {
            return null;
        }
        Class<? extends AbilitySlice> clazz = formController.getRoutePageSlice(intent);
        if (clazz == null) {
            return null;
        }
        return clazz.getName();
    }

    // 为了方便演示，不在Ability实现流转逻辑，具体逻辑在AbilitySlice中实现
    @Override
    public boolean onStartContinuation() {
        HiLog.info(TAG, "onStartContinuation called");
        return true;
    }

    @Override
    public boolean onSaveData(IntentParams saveData) {
        HiLog.info(TAG, "onSaveData called");
        return true;
    }

    @Override
    public boolean onRestoreData(IntentParams restoreData) {
        HiLog.info(TAG, "onRestoreData called");
        return true;
    }

    @Override
    public void onCompleteContinuation(int result) {
        HiLog.info(TAG, "onCompleteContinuation called");
    }



}
